<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Service_Basic extends Controller_Service {

    protected $_data = null;
    protected $_status = "";
    protected $_message = "";
    protected $_export_type = "";
    protected $_customer = null;
    protected $_api_key = "";
    protected $_token = "";

    public function before() {
        parent::before();
        $controller = strtolower($this->request->controller());
        if ($controller != 'auth') {
            $token = Arr::get($_REQUEST, 'token');
            if (empty($token)) {
                $this->setStatus(Controller_Helper_Api::API_STATUS_PARAM_MISSING);
                $this->setMessage(Controller_Helper_Api::API_MESSAGE_PARAM_MISSING);
                $this->export();
            }
            // add token
            $this->_token = $token;
            $s_cus_ses = new Model_Service_Session_User();
            $s_customer = new Model_Service_User();
            $o_entity_cus_ses = $s_cus_ses->get_by_session_key($token)->get_data();
            $this->_customer = $s_customer->load($o_entity_cus_ses->getCustomer_Id())->get_data();
            if ($o_entity_cus_ses->getId() <= 0) {
                $this->setStatus(Controller_Helper_Api::API_AUTH_STATUS_SESSION_INVALID);
                $this->setMessage(Controller_Helper_Api::API_AUTH_MESSAGE_SESSION_INVALID);
                $this->export();
            } else {
                $todays_date = date("Y-m-d H:i:s", strtotime("now"));
                $today = strtotime($todays_date);
                $expiration_date = strtotime($o_entity_cus_ses->getExpired());
                if ($expiration_date <= $today) {
                    $this->setStatus(Controller_Helper_Api::API_AUTH_STATUS_SESSION_EXPIRED);
                    $this->setMessage(Controller_Helper_Api::API_AUTH_MESSAGE_SESSION_EXPIRED);
                    $this->export();
                }
                //get profile
                $en_cus_pro = $this->_customer->get_customerprofile()->get_data();
                $this->_customer->set__Gender($en_cus_pro->getGender());
                $this->_customer->set__Dob($en_cus_pro->getDob());
                //get deviceid

            }
        }
    }

    /**
     * export to json,xml,html
     */
    public function export() {
        header('Access-Control-Allow-Origin: *');
        $s_export_type = Arr::get($_REQUEST, "export");
        if (empty($this->_export_type)) {
            if (isset($s_export_type) && !empty($s_export_type)) {
                $this->_export_type = strtolower(trim($s_export_type));
            } else {
                $this->_export_type = Controller_Helper_Constant::SERVICE_DEFAULT_EXPORT;
            }
        }
        if ($this->_export_type === 'html') {
            $this->to_html();
        } else if ($this->_export_type === 'xml') {
            $this->to_xml();
        } else {
            $this->to_json();
        }

        die;
    }

    /**
     * return string json
     */
    public function to_json() {
        ob_clean();
        $a_json = array();
        $a_json[Controller_Helper_Constant::SERVICE_STATUS] = $this->_status;
        $a_json[Controller_Helper_Constant::SERVICE_MESSAGE] = $this->_message;
        if (is_array($this->_data)) {
            $a_json[Controller_Helper_Constant::SERVICE_RESULT] = $this->_data;
        }

        echo json_encode($a_json);
    }

    /**
     * return string json
     */
    public function to_html() {
        ob_clean();
        $a_json = array();
        $a_json[Controller_Helper_Constant::SERVICE_STATUS] = $this->_status;
        $a_json[Controller_Helper_Constant::SERVICE_MESSAGE] = $this->_message;
        if (is_array($this->_data)) {
            $a_json[Controller_Helper_Constant::SERVICE_RESULT] = $this->_data;
        }
        echo "<PRE>";
        print_r($a_json);
    }

    /**
     * to_xml
     */
    public function to_xml() {
        ob_clean();
        header('Content-Type: text/xml; charset=UTF-8');
        $a_xml = array();
        $a_xml[Controller_Helper_Constant::SERVICE_STATUS] = $this->_status;
        $a_xml[Controller_Helper_Constant::SERVICE_MESSAGE] = $this->_message;
        //$a_xml['test']='test';
        if (is_array($this->_data)) {
            $a_xml[Controller_Helper_Constant::SERVICE_RESULT] = $this->_data;
        }
        $xml = Controller_Helper_Array2XML::createXML($this->_node_xml, $a_xml);
        echo ($xml->saveXML());
    }

    public function action_manager() {
        $api_key = Arr::get($_REQUEST, 'api_key');
        if ($api_key != $this->_api_key || empty($api_key)) {
            $this->setStatus(Controller_Helper_Api::API_404);
            $this->setMessage(Controller_Helper_Api::API_MESSAGE_404);
            $this->export();
        }

        $directory = dirname(__FILE__);
        $data = array();
        if ($handle = opendir($directory)) {
            $i = -1;
            $is_add_i = true;
            while (false !== ($entry = readdir($handle))) {
                if ($entry != "." && $entry != "..") {
                    if (file_exists($directory . "/" . $entry) && $entry != "Basic.php") {
                        $file = fopen($directory . "/" . $entry, 'r');
                        $request = array();
                        while (!feof($file)) {
                            $code = fgets($file);
                            if (strpos($code, ' action_')) {
                                if ($is_add_i) {
                                    $i++;
                                }
                                $a_code = explode(" action_", $code);
                                $a_code = explode("()", $a_code[1]);
                                $action = $a_code[0];
                                $request = array();
                                $controller = strtolower(str_replace(".php", "", $entry));
                                $data[$i]['url'] = 'service/' . $controller . "/" . $action;
                                if ($controller != 'auth' && $controller != 'portal') {
                                    $request[] = 'session_key';
                                }
                                $data[$i]['parame'] = $request;
                                $is_add_i = true;
                            } else if (strpos($code, '$_REQUEST')) {

                                $a_code = explode('$_REQUEST', $code);
                                $str_request = str_replace("'", "", $a_code[1]);
                                $str_request = str_replace('"', "", $str_request);
                                $str_request = str_replace(' ', "", $str_request);
                                $str_request = str_replace(',', "", $str_request);
                                $a_code = explode(')', $str_request);
                                $request[] = $a_code[0];
                                $data[$i]['parame'] = $request;
                            } else if (strpos($code, '* @todo:')) {
                                $i++;
                                $is_add_i = false;
                                $a_code = explode('* @todo:', $code);
                                $data[$i]['decription'] = $a_code[1];
                            }
                        }
                        fclose($file);
                    }
                }
            }
            closedir($handle);
        }
        $this->setData($data);
        $this->export();
    }

    public function get_permission($content_id, $subscription, $customer_id, $deviceid, $type) {
        //return 1;
        $s_con_sub = new Model_Service_Content_Subscription();
        $has = 0;
        if(!empty($subscription)){
            $has = $s_con_sub->get_subscriptions_and_content($content_id, $subscription);
        }
        if ($has == 0) {
            // check buy item
            $s_order = new Model_Service_Order();
            $has = $s_order->check_item($deviceid, $customer_id, $content_id, $type);
        }
        return $has;
    }
    public function url_to_buy($url) {
        $url_to_buy = Controller_Helper_Url::get_domain() ."/login_mobile.html?token=".md5($this->_token)."&redirect=".urlencode($url);
        return $url_to_buy;
    }
}

?>
